﻿namespace Blaze.Editor.Dev.DevPanels
{
    using System;
    using System.IO;
    using Build;
    using EditorOnly;
    using Framework;
    using Framework.LuaExtensions;
    using UnityEditor;
    using UnityEditor.SceneManagement;
    using UnityEngine;
    using UnityEngine.UI;

    /// <summary>
    /// 工作流开发面板。
    /// </summary>
    public class WorkflowDevPanel : DevPanel
    {
        /// <summary>
        /// 获取面板上显示的功能名称。
        /// </summary>
        public override string Name
        {
            get { return "工作流"; }
        }

        /// <summary>
        /// 当需要绘制面板时调用此方法。
        /// </summary>
        public override void OnGUI()
        {
            GUILayout.BeginVertical();
            GUILayout.BeginHorizontal();
            GUILayout.Label("界面名称：", GUILayout.Width(54));
            mModuleName = EditorGUILayout.TextField(mModuleName);
            mAutoOverwrite = GUILayout.Toggle(mAutoOverwrite, "强制覆盖已有资源");
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();

            if (GUILayout.Button("创建界面"))
                rapidCreateUIResources(mModuleName, mAutoOverwrite);
        }

        private void createLuaScripts(string moduleName, bool autoOverwrite)
        {
            var dir = ProjectPath.Get("Lua/UI/" + moduleName);
            if (!autoOverwrite && Directory.Exists(dir))
                throw new InvalidOperationException("Lua文件夹已存在 -> " + dir);
            Directory.CreateDirectory(dir);

            var templateFile = ProjectPath.GetAssets("Blaze/Editor/EditorResources/LuaTemplates/UI.lua");
            var content = File.ReadAllText(templateFile);
            content = content.Replace("{comments}", mModuleName);
            var outputFile = $"{dir}/{moduleName}UI.lua";
            File.WriteAllText(outputFile, content);
        }

        private void rapidCreateUIResources(string modueName, bool autoOverwrite)
        {
            if (string.IsNullOrEmpty(modueName))
                throw new ArgumentException();
            var dir = BuildSettings.GetDynamicResourceRelativePath("UI/" + modueName, false);
            if (!autoOverwrite && Directory.Exists(dir))
            {
                Debug.LogError("文件夹已存在 -> " + dir);
                return;
            }

            Directory.CreateDirectory(dir);
            AssetDatabase.Refresh();
            var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
            var sceneDir = BuildSettings.GetDynamicResourceRelativePath(string.Format("UI/{0}/{0}.unity", modueName), true);

            var cameraObj = new GameObject("Camera");
            var camera = cameraObj.AddComponent<Camera>();
            camera.orthographic = true;
            camera.orthographicSize = 5;

            var rootObj = new GameObject(string.Format("{0}UI", modueName));
            rootObj.AddComponent<RectTransform>();

            var canvas = rootObj.AddComponent<Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceCamera;
            canvas.worldCamera = camera;

            var canvasScaler = rootObj.AddComponent<CanvasScaler>();
            canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            canvasScaler.referenceResolution = new Vector2(1280, 720);

            rootObj.AddComponent<GraphicRaycaster>();
            var luaBehaviour = rootObj.AddComponent<LuaBehaviour>();
            luaBehaviour.LuaFilePath = string.Format("UI/{0}/{0}UI", modueName);
            rootObj.SetLayer("UI", true);

            PrefabUtility.CreatePrefab(BuildSettings.GetDynamicResourceRelativePath(string.Format("UI/{0}/{0}UI.prefab", modueName), true), rootObj, ReplacePrefabOptions.ConnectToPrefab);
            AssetDatabase.SaveAssets();

            EditorSceneManager.SaveScene(scene, sceneDir);

            createLuaScripts(modueName, autoOverwrite);
            AssetDatabase.Refresh();
        }

        private string mModuleName = "MyModule";
        private bool mAutoOverwrite;
    }
}